package com.hl.toolkit.pay.controller;

import com.alibaba.fastjson.JSON;
import com.tencent.util.GetWxOrderno;
import com.tenpay.other.demo.QQpayScann;
import com.tycoin.account.slaveentity.TycoinAccountRecharge;
import com.tycoin.account.slaveservice.TycoinAccountRechargeCallbackProcessService;
import com.tycoin.account.slaveservice.TycoinAccountRechargeService;
import com.tycoin.user.slaveentity.TycoinUser;
import com.tycoin.user.slaveservice.TycoinUserService;
import com.util.*;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * QQ支付
 */
@Controller
@RequestMapping(value = { "/interface/QQPay" })
public class QQScannController extends AbstractController {

	private static final Logger logger = LoggerFactory.getLogger(QQScannController.class);

	@Autowired
	private TycoinAccountRechargeService tycoinAccountRechargeService;
	@Autowired
	private TycoinAccountRechargeCallbackProcessService tycoinAccountRechargeCallbackProcessService;

	@Autowired
	private TycoinUserService tycoinUserService;

	@RequestMapping(value = "/scannPay", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public String testTradePrecreate(HttpServletRequest request, HttpServletResponse response) {
		String resultStr = "";
		TycoinAccountRecharge tycoinAccountRecharge = new TycoinAccountRecharge();
		String total_fee = request.getParameter("totalFee");
		String auth_code = request.getParameter("authCode");
		String addip = IpRequestUtils.getRemoteHost(request);
		String userId = request.getParameter("userId");
		String Logno = request.getParameter("Logno");
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long currentInt = System.currentTimeMillis();
		String order_create_time = formatter.format(currentInt);
		String order_create_time3 = formatter3.format(currentInt);
		tycoinAccountRecharge.setLogno(RandomUtils.getRandomString(16));
		String outTradeNo = "QQTran" + currentInt + (long) (Math.random() * 1000000000L);
		tycoinAccountRecharge.setMoney(String.valueOf(Integer.valueOf(total_fee)));
		tycoinAccountRecharge.setMoneyfloat(((float) Integer.valueOf(total_fee)) / 100);
		tycoinAccountRecharge.setUserId(userId);
		tycoinAccountRecharge.setPaymentTime(order_create_time3);
		tycoinAccountRecharge.setDateTime(currentInt);
		tycoinAccountRecharge.setPaymentStatus(0);
		tycoinAccountRecharge.setAddip(addip);
		tycoinAccountRecharge.setPayMode(4);
		tycoinAccountRecharge.setPaymentId(outTradeNo);
		tycoinAccountRechargeService.save(tycoinAccountRecharge);
		QQpayScann qQpayScann = new QQpayScann();
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			resultMap = qQpayScann.qpayMicroPay(total_fee, auth_code, tycoinAccountRecharge.getPaymentId());
			String transaction_id = resultMap.get("transaction_id");

			resultMap.put("transaction_id", outTradeNo);
			JSONObject jsonObject = JSONObject.fromObject(resultMap);
			resultStr = jsonObject.toString();
			tycoinAccountRecharge.setReturnText(resultStr);
			// "result_code":"SUCCESS","retcode":"0","retmsg":"ok","return_code":"SUCCESS"
			String result_code = resultMap.get("result_code");
			tycoinAccountRecharge.setPaymentId(outTradeNo);

			if (!StringUtil.isNull(Logno)) {
				tycoinAccountRecharge.setLogno(Logno);
			} else {
				tycoinAccountRecharge.setLogno(RandomUtils.getRandomString(16));
			}
			tycoinAccountRecharge.setShopTradeNo(transaction_id);

			String retcode = resultMap.get("retcode");
			String return_code = resultMap.get("result_code");
			if ("SUCCESS".equals(return_code) && "SUCCESS".equals(return_code) && "0".equals(retcode)) {
				tycoinAccountRecharge.setPaymentStatus(1);
				tycoinAccountRechargeService.save(tycoinAccountRecharge);
			} else {
				tycoinAccountRecharge.setPaymentStatus(2);
				tycoinAccountRechargeService.save(tycoinAccountRecharge);
			}

		} catch (Exception e) {
		}

		return resultStr;

	}

	@RequestMapping(value = "/findScannPayByTran", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public String findScannPayByTran(String transaction_id, String out_trade_no) {
		/*
		 * String transaction_id = request.getParameter("transaction_id");
		 * String out_trade_no = request.getParameter("out_trade_no");
		 */
		String resultStr = "";
		Map<String, String> resultmap = new HashMap<String, String>();
		try {
			QQpayScann qQpayScann = new QQpayScann();
			resultmap = qQpayScann.qpayOrderQuery(transaction_id, out_trade_no);
			JSONObject jsonObject = JSONObject.fromObject(resultmap);
			String return_code = jsonObject.getString("return_code");
			String result_code = jsonObject.getString("result_code");
			if ("SUCCESS".equals(return_code)) {
				if ("SUCCESS".equals(result_code)) {
					jsonObject.put("code", jsonObject.getString("trade_state"));
					jsonObject.put("resultMessage", jsonObject.getString("trade_state_desc"));
				} else {
					jsonObject.put("code", jsonObject.get("err_code"));
					jsonObject.put("resultMessage", jsonObject.get("retmsg"));
				}
				jsonObject.put("returnMessage", "请求成功");
			} else {
				jsonObject.put("code", "ERROR");
				jsonObject.put("returnMessage", "请求出错");
			}

			resultStr = jsonObject.toString();
		} catch (Exception e) {
		}

		return resultStr;

	}

	/**
	 * return 返回二维码的链接，二维码图片流
	 **/

	@RequestMapping(value = "/tradePrecreate", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public String TradePrecreate(HttpServletRequest request, HttpServletResponse response) {
		String result = "";
		String qqPaymentSwitch = LoadProperties.loadPropertiesValue("qqPaymentSwitch");
		System.out.println(qqPaymentSwitch);
		if ("1".equals(qqPaymentSwitch)) {
			String outTradeNo = "QQTran" + System.currentTimeMillis() + (long) (Math.random() * 1000000000L);
			String Charge = request.getParameter("Charge");
			String GoodsName = request.getParameter("GoodsName");
			String UserId = request.getParameter("UserId");
			String AddIp = IpRequestUtils.getRemoteHost(request);

			Map<String, String> putMap = new HashMap<String, String>();
			putMap.put("Charge", Charge);
			putMap.put("GoodsName", GoodsName);
			putMap.put("UserId", UserId);
			result = isNotparam(putMap);
			if (StringUtil.isNotNull(result)) {
				return result;
			}

			TycoinAccountRecharge tycoinAccountRecharge = new TycoinAccountRecharge();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
			SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			long currentInt = System.currentTimeMillis();
			String order_create_time3 = formatter3.format(currentInt);

			tycoinAccountRecharge.setMoney(String.valueOf(Integer.valueOf(Charge)));
			tycoinAccountRecharge.setMoneyfloat((float) Integer.valueOf(Charge) / 100);

			tycoinAccountRecharge.setUserId(UserId);
			String Logno = request.getParameter("Logno");
			if (!StringUtil.isNull(Logno)) {
				tycoinAccountRecharge.setLogno(Logno);
			} else {
				Logno = RandomUtils.getRandomString(16);
				tycoinAccountRecharge.setLogno(Logno);
			}

			TycoinAccountRecharge tycoin = tycoinAccountRechargeService.findOneBylogno(Logno);
			if (tycoin != null && !StringUtil.isNull(String.valueOf(tycoin.getId()))) {
				result = "{\"result_code\":\"2001\",\"return_msg\":\" 订单号不能重复提交\"}";
				return result;
			}
			// 商家异步回调地址，可为空
			String qqPayNotifUrl = request.getParameter("qqPayNotifUrl");
			if (!StringUtil.isNull(qqPayNotifUrl)) {
				try {
					tycoinAccountRecharge.setShopNotifUrl(URLDecoder.decode(qqPayNotifUrl, "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}

			tycoinAccountRecharge.setPaymentId(outTradeNo);
			tycoinAccountRecharge.setPaymentTime(order_create_time3);
			tycoinAccountRecharge.setDateTime(currentInt);
			tycoinAccountRecharge.setPaymentStatus(0);
			tycoinAccountRecharge.setAddip(AddIp);
			tycoinAccountRecharge.setPayMode(4);

			QQpayScann qQpayScann = new QQpayScann();
			Map<String, String> resultMap = new HashMap<String, String>();
			try {
				resultMap = qQpayScann.qpayUnifiedOrder(Charge, GoodsName, outTradeNo);
				String prepay_id = resultMap.get("prepay_id");
				tycoinAccountRecharge.setReturnText(JSON.toJSONString(resultMap));
				tycoinAccountRechargeService.save(tycoinAccountRecharge);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String url = resultMap.get("code_url");
			// JSONObject jsonObject = JSONObject.fromObject(resultMap);
			/// resultStr=jsonObject.toString();
			result = "{\"result_code\":\"0000\",\"return_msg\":\"\",\"imgpayUrl\":\"" + url + "\",\"transaction_id\":\""
					+ outTradeNo + "\"}";
		} else {
			result = "{code:\"NOTICE\",resultMessage:\"对不起，QQ钱包支付通道已关闭\"}";
		}
		return result;
	}

	@RequestMapping(value = "/qpayRefundByTran", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public String qpayRefundByTran(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> resultMap = new HashMap<String, String>();
		String out_trade_no = request.getParameter("outTradeNo");
		String refund_fee = request.getParameter("refundFee");
		String resultStr = "";
		Map<String, String> resultmap = new HashMap<String, String>();
		boolean status = false;
		try {
			QQpayScann qQpayScann = new QQpayScann();
			resultmap = qQpayScann.qpayRefund(out_trade_no, refund_fee);
			String result_code = resultMap.get("result_code");
			String return_code = resultMap.get("return_code");
			TycoinAccountRecharge tycoinAccountRecharge = tycoinAccountRechargeService.findOneBypaymentId(out_trade_no);
			if ("SUCCESS".equals(result_code) && "SUCCESS".equals(return_code)) {
				boolean boo = tycoinAccountRechargeCallbackProcessService
						.tycoinAccountRechargeCallBackSaveOrUpdate(tycoinAccountRecharge, request, response);
				status = boo;
			}
			JSONObject jsonObject = JSONObject.fromObject(resultmap);
			jsonObject.put("boo", status);
			resultStr = jsonObject.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultStr;

	}

	@RequestMapping(value = "/notiyReturn", method = RequestMethod.POST)
	public String notiyReturn(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String result = "";
		System.out.println("------------我已经进入了QQ异步回调----------");

		System.out.println("----接收微信发来的消息---");
		BufferedReader reader = request.getReader();
		String line = "";
		StringBuffer inputString = new StringBuffer();
		try {
			while ((line = reader.readLine()) != null) {
				inputString.append(line);
			}
			request.getReader().close();
			System.out.println("----接收到的报文---" + inputString.toString());

			Map maps = GetWxOrderno.doXMLParse(inputString.toString());

			// Map<Object, Object> map =
			// XMLUtil.doXMLParse(inputString.toString());
			for (Object keyValue : maps.keySet()) {
				System.out.println(keyValue + "=" + maps.get(keyValue));
			}
			System.out.println("===============trade_state:" + maps.get("trade_state"));
			String out_trade_no = maps.get("out_trade_no").toString();
			String total_fee = maps.get("total_fee").toString();
			String trade_no = maps.get("transaction_id").toString();
			/*
			 * String uid=request.getParameter("uid"); String
			 * type=request.getParameter("type");
			 * System.out.println("uid>>>>>>>>>>:"+uid);
			 * System.out.println("type>>>>>>>>>>:"+type);
			 */
			// String uid = new
			// String(request.getParameter("uid").getBytes("ISO-8859-1"),"UTF-8");
			System.out.println("----TRADE_FINISHED:" + out_trade_no);
			TycoinAccountRecharge tycoinAccountRecharge = tycoinAccountRechargeService.findOneBypaymentId(out_trade_no);

			/**
			 * 
			 * SUCCESS 支付成功
			 * 
			 * REFUND 转入退款
			 * 
			 * REVOKED订单已撤销
			 * 
			 * CLOSED 订单已关闭
			 * 
			 * USERPAYING 用户支付中
			 * 
			 */
			JSONObject object = JSONObject.fromObject(findScannPayByTran(trade_no, out_trade_no));
			String trade_state = maps.get("trade_state").toString();
			trade_state = object.getString("trade_state");
			String resultMessage = "";
			if ("SUCCESS".equals(trade_state)) {
				resultMessage = "支付成功";
			} else if ("REFUND".equals(trade_state)) {
				resultMessage = "转入退款";
			} else if ("REVOKED".equals(trade_state)) {
				resultMessage = "订单已撤销";

			} else if ("CLOSED".equals(trade_state)) {
				resultMessage = "订单已关闭";
			} else if ("USERPAYING".equals(trade_state)) {
				resultMessage = "用户支付中";
			}
			System.out.println("状态：" + trade_state + ";信息：" + resultMessage);
			if (trade_state.equalsIgnoreCase("SUCCESS") && tycoinAccountRecharge != null) {
				System.out.println("------------回调修改状态-------------");
				if (tycoinAccountRecharge.getPaymentStatus() != 1) {
					System.out.println("--------------经过判断---------------");
					tycoinAccountRecharge.setPaymentStatus(1);
					tycoinAccountRecharge.setReturnText(JSON.toJSONString(maps));
					tycoinAccountRecharge.setShopTradeNo(trade_no);
					tycoinAccountRechargeService.save(tycoinAccountRecharge);
					String shopNotifUrl = tycoinAccountRecharge.getShopNotifUrl();
					if (StringUtil.isNotNull(shopNotifUrl)) {
						System.out.println("开始商户异步回调shopNotifUrl=" + shopNotifUrl + "&resultMessage=" + resultMessage
								+ "&code=" + trade_state + "&TradeNo=" + tycoinAccountRecharge.getShopTradeNo()
								+ "&paymentId=" + tycoinAccountRecharge.getPaymentId());
						HttpClientUtils hct = new HttpClientUtils();
						hct.get(shopNotifUrl + "&resultMessage=" + resultMessage + "&code=" + trade_state + "&TradeNo="
								+ tycoinAccountRecharge.getShopTradeNo() + "&paymentId="
								+ tycoinAccountRecharge.getPaymentId());
					}
					TycoinUser tycoinUser = tycoinUserService.findById(Long.valueOf(tycoinAccountRecharge.getUserId()));
					if (tycoinUser != null && StringUtil.isNotNull(String.valueOf(tycoinUser.getId()))) {
						tycoinAccountRechargeCallbackProcessService.rechargeCallbackProcess(tycoinAccountRecharge);
					}
				}
				result = "success";
			} else {
				if (tycoinAccountRecharge != null) {
					String shopNotifUrl = tycoinAccountRecharge.getShopNotifUrl();
					if (StringUtil.isNotNull(shopNotifUrl)) {
						HttpClientUtils hct = new HttpClientUtils();
						hct.get(shopNotifUrl + "&resultMessage=" + resultMessage + "&code=" + trade_state + "&TradeNo="
								+ tycoinAccountRecharge.getShopTradeNo() + "&paymentId="
								+ tycoinAccountRecharge.getPaymentId());
					}
				}

				else {
					tycoinAccountRecharge.setPaymentStatus(5);
					tycoinAccountRecharge.setShopTradeNo(trade_no);
					tycoinAccountRechargeService.save(tycoinAccountRecharge);

				}
			}
		} catch (Exception e) {
			e.getStackTrace();
		}
		return result;

	}

	/**
	 * 批量查询订单更新状态 根据userId
	 * @param userId
	 * @return
	 */
	@RequestMapping(value="batch_query_update_status")
	@ResponseBody
	public Map<String,Object> Batch_query_update_status(String userId){
		Map<String,Object> resultMap=new HashMap<>();
		List<TycoinAccountRecharge> list=tycoinAccountRechargeService.getOrderInQqByUserId(userId);
		List<String> error=new ArrayList<>();
		List<String> update_order=new ArrayList<>();
		TycoinAccountRecharge tycoinAccountRecharge=new TycoinAccountRecharge();
		int updateCount=0;
		int ORDERNOTEXIST=0;
		int SYSTEMERROR=0;
		int existence=0;
		for (int i = 0; i < list.size(); i++) {
			QQpayScann qQpayScann = new QQpayScann();
			Map<String, String> resultmap=null;
			try {
				resultmap = qQpayScann.qpayOrderQuery(list.get(i).getShopTradeNo(), list.get(i).getPaymentId());
			} catch (Exception e) {
				
				e.printStackTrace();
			}
			String return_code = resultmap.get("return_code");
			String result_code = resultmap.get("result_code");
			
			if ("SUCCESS".equals(return_code)){
				if ("SUCCESS".equals(result_code)) {
					String trade_state = resultmap.get("trade_state");
					tycoinAccountRecharge=list.get(i);
					if(trade_state.equals("SUCCESS")){//支付成功
						if(list.get(i).getPaymentStatus()!=1){							
							tycoinAccountRecharge.setPaymentStatus(1);
							tycoinAccountRechargeService.save(tycoinAccountRecharge);
							++updateCount;
							update_order.add("修改为成功的订单号有："+list.get(i).getPaymentId());
						}						
					}else if(trade_state.equals("REFUND")){//退款成功
						if(list.get(i).getPaymentStatus()!=4){
							tycoinAccountRecharge.setPaymentStatus(4);
							tycoinAccountRechargeService.save(tycoinAccountRecharge);
							++updateCount;
							update_order.add("修改为退款的订单号有："+list.get(i).getPaymentId());
						}
					}else if(trade_state.equals("CLOSED") || trade_state.equals("REVOKED") ){//支付失败
						if(list.get(i).getPaymentStatus()!=2){
							tycoinAccountRecharge.setPaymentStatus(2);	
							tycoinAccountRechargeService.save(tycoinAccountRecharge);
							++updateCount;
							update_order.add("修改为失败的订单号有："+list.get(i).getPaymentId());
						}
					}else if(trade_state.equals("USERPAYING")){//正在支付
						if(list.get(i).getPaymentStatus()!=0){					
							tycoinAccountRecharge.setPaymentStatus(0);
							tycoinAccountRechargeService.save(tycoinAccountRecharge);
							++updateCount;
							update_order.add("修改为支付中的的订单号有："+list.get(i).getPaymentId());
						}
					}	
					++existence;
				}else{
					if("ORDERNOTEXIST".equals(resultmap.get("err_code"))){
						error.add("原因："+resultmap.get("retmsg")+",订单号:"+list.get(i).getPaymentId());
						++ORDERNOTEXIST;
					}else if("SYSTEMERROR".equals(resultmap.get("err_code"))){
						error.add("原因："+resultmap.get("retmsg")+",订单号:"+list.get(i).getPaymentId());
						++SYSTEMERROR;
					}
				}				
			} else {
				resultMap.put("return_msg","请求失败！" );
			}			
		}
		resultMap.put("retmsg",error);
		resultMap.put("count","查询到该账户下QQ支付共有"+list.size()+"条订单！" );
		resultMap.put("update_status","本次共修改"+updateCount+"条！");
		resultMap.put("existence","订单存在共有"+existence+"条！");
		resultMap.put("ORDERNOTEXIST","订单不存在共有"+ORDERNOTEXIST+"条！");
		resultMap.put("SYSTEMERROR","系统错误共有"+SYSTEMERROR+"条！");
		resultMap.put("update_order",update_order);
		if((existence+ORDERNOTEXIST+SYSTEMERROR)==list.size()){
			resultMap.put("correct_number","存在与不存在订单总条数正确");
		}else{
			resultMap.put("correct_number","存在与不存在订单总条数不正确");
		}
		return resultMap;
	}

}
